import com.hjl.jdbc.dao.EmpDao;
import com.hjl.jdbc.entity.Emp;
import org.apache.commons.dbcp.BasicDataSource;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

/**
 * @author ServivE
 * @version 0.1
 * @className MyDemo
 * @description
 * @date 2024/8/7 10:34
 * @since jdk11
 */
public class MyDemo {
    ApplicationContext ac = null;
    EmpDao empDao = null;

    @Before
    public void init() {
        ac = new ClassPathXmlApplicationContext("jdbc.xml");
        empDao = (EmpDao) ac.getBean("empDao");
    }

    @Test
    public void basicDsTest() throws SQLException {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///comdb");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        dataSource.setInitialSize(10);//初始连接数
        dataSource.setMaxActive(10);
        dataSource.setMaxIdle(8);
        dataSource.setMinIdle(2);
        dataSource.setMaxWait(30000);
        Connection connection = dataSource.getConnection();
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery("select * from emp");
        while (resultSet.next()) {
            System.out.println(resultSet.getInt(1) + " " + resultSet.getString(2));
        }
    }

    /*jdbcTemplateTest*/
    @Test
    public void testGetAllEmps() {
        EmpDao empDao = ac.getBean("empDao", EmpDao.class);
        List<Emp> allEmps = empDao.getAllEmps();
        allEmps.forEach(emp -> System.out.println(emp));
    }

    @Test
    public void addEmp() {

        Emp e = new Emp();
        e.setEname("aaaa");
        e.setEsex("男");
        e.setSal("3000");
        System.out.println(empDao.addEmp(e));
    }

    @Test
    public void getEmpById() {
        Emp emp = empDao.getEmpById(4);
        System.out.println(emp.getEname());
    }
}
